package org.hako.recite.word.parser.impl;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.hako.recite.word.model.Word;
import org.hako.recite.word.parser.WordList;
import org.hako.recite.word.parser.WordListParseException;

/**
 * Word list parser for data file whose extension is {@code dat}.
 * 
 * @since 0.4.7
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class DataFileWordListParser extends AbstractWordListParser {

	@Override
	public WordList parse(InputStream inputStream)
			throws WordListParseException {
		DataInputStream stream = new DataInputStream(inputStream);
		try {
			int columnCount = stream.readInt();
			int rowCount = stream.readInt() + 1;
			WordList wordList = new WordList();
			for (int row = 0; row < rowCount; row++) {
				String[] cells = new String[columnCount];
				for (int column = 0; column < columnCount; column++) {
					cells[column] = stream.readUTF();
				}
				if (row == 0) {
					wordList.setColumnTitles(cells);
				} else {
					wordList.addWord(new Word(cells));
				}
			}
			return wordList;
		} catch (IOException e) {
			throw new WordListParseException(e);
		}
	}

}
